package com.atguigu.jxc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.jxc.dao.DamageListDao;
import com.atguigu.jxc.dao.DamageListGoodsDao;
import com.atguigu.jxc.entity.DamageList;
import com.atguigu.jxc.entity.DamageListGoods;
import com.atguigu.jxc.entity.User;
import com.atguigu.jxc.service.DamageListGoodsService;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DamageListGoodsServiceImpl implements DamageListGoodsService {

    @Autowired
    private DamageListDao damageListDao;

    @Autowired
    private DamageListGoodsDao damageListGoodsDao;
    @Autowired
    private HttpSession session;

    @Transactional
    @Override
    public void save(DamageList damageList, String damageListGoodsStr) {
        User user = (User)session.getAttribute("currentUser");
        System.out.println(user);
        damageList.setUserId(user.getUserId());
        damageListDao.save(damageList);
        Integer damageListId = damageList.getDamageListId();
        List<DamageListGoods> damageListGoods = JSONObject.parseArray(damageListGoodsStr, DamageListGoods.class);
        if (!CollectionUtils.isEmpty(damageListGoods)){
            for (DamageListGoods damageListGood : damageListGoods) {
                damageListGood.setDamageListId(damageListId);
                damageListGoodsDao.save(damageListGood);
            }
        }

    }

    @Override
    public List<DamageList> getList(String sTime, String eTime) {
        List<DamageList> damageList = damageListDao.getlist(sTime,eTime);
        return damageList;
    }

    @Override
    public List<DamageListGoods> goodsList(Integer damageListId) {
        List<DamageListGoods> damageListGoods = damageListGoodsDao.goodsList(damageListId);
        return damageListGoods;
    }
}
